package cn.com.xjnt.vas.web.manage.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.frameworks.core.logger.annotation.RunLogger;
import com.frameworks.core.web.controller.BaseController;
import com.frameworks.core.web.page.WebPage;
import com.frameworks.core.web.result.DataResult;
import com.frameworks.core.web.result.MsgResult;
import com.frameworks.core.web.search.DynamicSpecifications;
import com.frameworks.core.web.widget.TreeView;
import com.frameworks.core.web.widget.TreeView.NodeType;
import com.frameworks.core.web.widget.TreeView.State;
import com.google.common.collect.Lists;

import cn.com.xjnt.vas.manage.domain.entity.Region;
import cn.com.xjnt.vas.manage.domain.vo.RegionVo;
import cn.com.xjnt.vas.manage.service.RegionService;

/**
 * 类说明：
 * 
 * @author 作者 LUXIN
 * @version 创建时间：2016年5月5日 上午11:08:55
 */
@Controller
@RequestMapping("/manage/region")
public class RegionController extends BaseController {

    private static final String VIEW_PAGE = "manage/region/view";
    private static final String FORM_PAGE = "manage/region/form";

    @Autowired
    private RegionService regionService;
    @Autowired
    private Mapper mapper;

    protected RegionService getService() {
        return regionService;
    }

    /**
     * view页面
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Region:show" })
    @RequestMapping(value = "", method = { RequestMethod.GET })
    public ModelAndView show(HttpServletRequest request) {
        return new ModelAndView(VIEW_PAGE);
    }

    /**
     * view页面list方法
     * 
     * @param request
     * @param webPage
     * @return
     */
    @RequiresPermissions(value = { "Region:show" })
    @RequestMapping(value = "/list", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult list(HttpServletRequest request, WebPage webPage) {
        DataResult dataRet = new DataResult();
        try {
            Specification<Region> specification = DynamicSpecifications.bySearchFilter(request, Region.class);
            List<Region> models = getService().findByCondition(specification, webPage);
            List<RegionVo> lstVo = Lists.newArrayList();
            for (Region model : models) {
                RegionVo vo = mapper.map(model, RegionVo.class);
                lstVo.add(vo);
            }
            dataRet.pushOk("获取数据列表成功！");
            dataRet.setTotal(webPage.getTotalCount());
            dataRet.setRows(lstVo);
        } catch (Exception e) {
            dataRet.pushError("获取数据列表失败！");
            logger.error("获取数据列表异常！", e);
        }
        return dataRet;
    }
    /**
     * 树
     * @param id
     * @return
     */
    @RequiresPermissions(value = { "Region:show" })
    @RequestMapping(value = "/tree", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public List<TreeView> tree(Long id) {
        List<TreeView> treeViews = Lists.newArrayList();
        try {
            List<Region> regions = getService().findByParentId(id);
            for (Region model : regions) {
                TreeView treeView = new TreeView();
                treeView.setId(model.getId().toString());
                Region parent = model.getParent();
                treeView.setParent(parent == null ? "#" : parent.getId().toString());
                treeView.setText(model.getName());
                treeView.setChildren(model.getChildren().isEmpty() ? false : true);
                treeView.setType(treeView.getChildren() ? NodeType.folder : NodeType.item);
                switch (treeView.getType()) {
                case folder:
                    treeView.setIcon(TreeView.ICON_FOLDER);
                    break;
                case item:
                    treeView.setIcon(TreeView.ICON_ITEM);
                    break;
                }
                treeView.setLevel(String.valueOf(model.getLevel()));
                State state = new State();
                if (treeView.getChildren() && (model.getLevel() < 1)) {
                    state.setOpened(true);
                    state.setSelected(true);
                }
                treeView.setState(state);
                treeViews.add(treeView);
            }
        } catch (Exception e) {
            logger.error("获取区域树异常！", e);
        }
        return treeViews;
    }
    /**
     * 新增
     * 
     * @param request
     * @return
     */
    @RequiresPermissions(value = { "Region:show" })
    @RequestMapping(value = "/add", method = { RequestMethod.GET })
    public ModelAndView add(HttpServletRequest request) {
        return new ModelAndView(FORM_PAGE);
    }

    /**
     * 修改
     * 
     * @param id
     * @return
     */
    @RequiresPermissions(value = { "Region:show" })
    @RequestMapping(value = "/edit/{id}", method = { RequestMethod.GET })
    public ModelAndView edit(@PathVariable("id") Long id) {
        ModelAndView mav = new ModelAndView(FORM_PAGE);
        Region model = getService().findById(id);
        mav.addObject("region", model);
        return mav;
    }

    /**
     * 保存
     * 
     * @param entity
     * @return
     */
    @RunLogger(value = "添加地区", isSaveRequest = true)
    @RequiresPermissions(value = { "Region:add" })
    @RequestMapping(value = "/add", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult store(Region entity) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().save(entity);
            msgRet.pushOk("添加成功！");
        } catch (Exception e) {
            msgRet.pushError("添加失败：" + e.getMessage());
            logger.error("添加时，发生异常！", e);
        }
        return msgRet;
    }

    /**
     * 更新
     * @param entity
     * @return
     */
    @RunLogger(value = "编辑地区", isSaveRequest = true)
    @RequiresPermissions(value = { "Region:modify" })
    @RequestMapping(value = "/edit", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult modify(Region entity) {
        MsgResult msgRet = new MsgResult();
        try {
            getService().update(entity);
            msgRet.pushOk("修改成功!");
        } catch (Exception e) {
            msgRet.pushError("修改失败：" + e.getMessage());
            logger.error("修改时，发生异常！", e);
        }
        return msgRet;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @RunLogger(value="删除地区", isSaveRequest=true)
    @RequiresPermissions(value={"Region:remove"})
    @RequestMapping(value="/remove/{id}", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@PathVariable("id") Long id){
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteById(id);
            msgRet.pushOk("删除成功！");
        } catch(Exception e) {
            msgRet.pushError("删除失败：" + e.getMessage());
            logger.error("删除时，发生异常！", e);
        }
        return msgRet;
    }
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RunLogger(value="批量删除地区", isSaveRequest=true)
    @RequiresPermissions(value={"Region:remove"})
    @RequestMapping(value="/remove", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public MsgResult remove(@RequestParam("ids[]") Long[] ids){
        MsgResult msgRet = new MsgResult();
        try {
            getService().deleteByIds(ids);
            msgRet.pushOk("批量删除成功!");
        } catch(Exception e) {
            msgRet.pushError("批量删除失败：" + e.getMessage());
            logger.error("批量删除时，发生异常！", e);
        }
        return msgRet;
    }
    /**
     * 根据pid获取地区列表
     * @param id
     * @return
     */
    @RequestMapping(value="/getRegionByPid/{pId}", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public DataResult getRegionByPid(@PathVariable("pId") Long id){
        DataResult dataRet = new DataResult();
        try {
            List<Region> lists = getService().findByParentId(id);
            List<RegionVo> lvos = Lists.newArrayList();
            for (Region region : lists) {
                RegionVo vo = mapper.map(region, RegionVo.class);
                lvos.add(vo);
            }
            dataRet.setRows(lvos);
            dataRet.pushOk("获取地区列表成功!");
        } catch(Exception e) {
            dataRet.pushError("获取地区列表失败：" + e.getMessage());
            logger.error("获取地区列表时，发生异常！", e);
        }
        return dataRet;
    }
}
